﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
using System.Runtime.InteropServices;

//assistance for http://www.dotnet247.com/247reference/msgs/31/159934.aspx


namespace LastLogon
{
    [ComImport]
    [Guid("9068270B-0939-11D1-8BE1-00C04FD8D503")]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    internal interface IADsLargeInteger
    {
        [DispId(0x00000002)]
        int HighPart { get; set; }
        [DispId(0x00000003)]
        int LowPart { get; set; }
    }


    class MainProgram
    {
        static void Main(string[] args)
        {
            Domain domain = Domain.GetCurrentDomain();
            Forest forest = Forest.GetCurrentForest();
            System.IO.StreamWriter sw = new System.IO.StreamWriter("ad.csv");
            System.IO.StreamWriter sw2 = new System.IO.StreamWriter("debug.csv");

            if (domain.DomainControllers.Count > 0)
            {
                DirectorySearcher dsearch = domain.DomainControllers[0].GetDirectorySearcher();
                dsearch.Filter = "(objectClass=computer)";
                dsearch.PageSize = 15000;
                dsearch.SizeLimit = 15000;
                SearchResultCollection src = dsearch.FindAll();

                int dc_max = domain.DomainControllers.Count;
                int dc_count = 0;
                foreach (SearchResult sr in src)
                {
                    //Int64 lastLogon = 0;
                    //Int64 pwdLastSet = 0;
                    String operatingSystem = "";
                    String name = "empty";
                    String operatingSystemServicePack = "";
                    DateTime lastLogon = DateTime.MinValue;
                    DateTime pwdLastSet = DateTime.MinValue;
                    int dcLastLogon = 0;
                    int dcPwdLastSet = 0;
                    dc_count = 0;
                    do
                    {
                        DirectoryEntry de;
                        try
                        {
                            if (dc_count == 0)
                            {
                                de = sr.GetDirectoryEntry();
                                name = de.Name;

                                //String[] split = name.Split(new char[] {'='} );

                                

                            }
                            else
                            {
                                
                                DirectorySearcher dsearch2 = domain.DomainControllers[dc_count].GetDirectorySearcher();
                                dsearch2.Filter = name;
                                SearchResult sr2 = dsearch2.FindOne();

                                de = sr2.GetDirectoryEntry();
                            }


                            //Console.WriteLine(de.Name);

                            if (de.Properties["lastLogon"].Value != null)
                            {
                                IADsLargeInteger li = (IADsLargeInteger)de.Properties["lastLogon"].Value;
                                long date = (long)li.HighPart << 32 | (uint)li.LowPart;
                                DateTime lastlogonResult = DateTime.FromFileTime(date);
                                //Console.WriteLine(lastlogonResult.ToString());

                                if (lastlogonResult > lastLogon)
                                {
                                    lastLogon = lastlogonResult;
                                    dcLastLogon = dc_count;
                                }

                            }
                            if (de.Properties["pwdLastSet"].Value != null)
                            {
                                IADsLargeInteger li = (IADsLargeInteger)de.Properties["pwdLastSet"].Value;
                                long date = (long)li.HighPart << 32 | (uint)li.LowPart;
                                DateTime pwdLastSetResult = DateTime.FromFileTime(date);
                                //Console.WriteLine(pwdLastSetResult.ToString());

                                if (pwdLastSetResult > pwdLastSet)
                                {
                                    pwdLastSet = pwdLastSetResult;
                                    dcPwdLastSet = dc_count;
                                }

                            }
                            if (de.Properties["operatingSystem"].Value != null)
                            {
                                operatingSystem = (String)de.Properties["operatingSystem"].Value;
                                //Console.WriteLine(operatingSystem);
                            }

                            if (de.Properties["operatingSystemServicePack"].Value != null)
                            {
                                operatingSystemServicePack = (String)de.Properties["operatingSystemServicePack"].Value;
                                //Console.WriteLine(operatingSystem);
                            }

                            //Console.WriteLine("Name: {0}, pwdLastSet: {1}, lastLogon: {2}, OS: {3}, DC: {4}", 
                            //    name, 
                            //    pwdLastSet, 
                            //    lastLogon,
                            //    operatingSystem,
                            //    domain.DomainControllers[dc_count].Name);

                            sw2.WriteLine("{0},{1},{2},{3},{4}",
                                name,
                                pwdLastSet,
                                lastLogon,
                                operatingSystem,
                                domain.DomainControllers[dc_count].Name);
                            sw2.Flush();

                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine(e.ToString());
                        }
                        finally
                        {
                            dc_count++;
                            
                        }
                    } while (dc_count < dc_max);


                    String[] split = name.Split(new char[] { '=' });
                    String sIPAddress = "";
                    System.Net.IPAddress[] ipaddrs = null;
                    if (split.Length == 2)
                    {
                        try
                        {
                            ipaddrs = System.Net.Dns.GetHostAddresses(split[1]);
                            if (ipaddrs.Length == 1)
                            {
                                sIPAddress = ipaddrs[0].ToString();
                            }
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine(e.ToString());
                            sIPAddress = "UNKNOWN HOST";
                        }

                    }
                    

                    //System.Net.Dns.GetHostAddresses();

                    

                  Console.WriteLine("Name: {0}, pwdLastSet: {1}, lastLogon: {2}, DC: {3}", name, pwdLastSet, lastLogon,
                        domain.DomainControllers[dcLastLogon].Name);
                  sw.WriteLine(",,{0},,,,,,{1},,{2},{3},{4},,,?,{5},{6}", 
                      name, 
                      domain.Name,
                      operatingSystemServicePack,
                      lastLogon,
                      sIPAddress,
                      pwdLastSet,
                      domain.DomainControllers[dcLastLogon].Name);

                  sw.Flush();
                }



            }
            sw.Close();
            sw2.Close();


        }
    }
}
